<template>
	<view class="spinner-container" v-if="show">
		<view class="spinner-overlay" @click="hide"></view>
		<view class="spinner-wheel" :style="{ transform: `rotate(${rotation}deg)` }">
			<view v-for="(student, index) in students" :key="index" class="spinner-segment"
				:style="getSegmentStyle(index)">
				<text class="segment-text">{{ student.studentName }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "Spinner",
		props: {
			students: Array
		},
		data() {
			return {
				show: false,
				rotation: 0,
				selectedStudent: null
			};
		},
		methods: {
			showSpinner() {
				this.show = true;
				this.startRotation();
			},
			hide() {
				this.show = false;
			},
			startRotation() {
				let duration = 3000; // 转动时长
				let rotation = Math.floor(Math.random() * 360) + 360 * 5; // 随机旋转角度，至少旋转5圈
				let startTime = null;

				const rotate = (timestamp) => {
					if (!startTime) startTime = timestamp;
					let progress = timestamp - startTime;
					let easeOut = (t) => (--t) * t * t + 1; // 缓动函数
					this.rotation = easeOut(progress / duration) * rotation;
					if (progress < duration) {
						requestAnimationFrame(rotate);
					} else {
						this.finishRotation();
					}
				};
				requestAnimationFrame(rotate);
			},
			finishRotation() {
				let segmentAngle = 360 / this.students.length;
				let selectedIndex = Math.floor((360 - (this.rotation % 360)) / segmentAngle);
				this.selectedStudent = this.students[selectedIndex];
				uni.showToast({
					title: `选中学生：${this.selectedStudent.studentName}`,
					icon: 'success',
					duration:3000
				});
				setTimeout(() => {
					this.hide();
				}, 1500); // 延迟关闭时间
			},
			getSegmentStyle(index) {
				let segmentAngle = 360 / this.students.length;
				return {
					transform: `rotate(${index * segmentAngle}deg)`,
					backgroundColor: index % 2 === 0 ? '#ffdd57' : '#ffab57' // 交替颜色
				};
			}
		}
	};
</script>

<style scoped>
	.spinner-container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.spinner-overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.spinner-wheel {
		position: relative;
		width: 300rpx;
		height: 300rpx;
		border-radius: 50%;
		overflow: hidden;
		border: 5rpx solid #fff;
	}

	.spinner-segment {
		position: absolute;
		width: 50%;
		height: 50%;
		left: 50%;
		transform-origin: 0% 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.segment-text {
		writing-mode: vertical-rl;
		transform: rotate(180deg);
		color: #fff;
		font-weight: bold;
		text-align: center;
	}

	.spinner-pointer {
		position: absolute;
		top: -10rpx;
		left: 50%;
		width: 0;
		height: 0;
		border-left: 10rpx solid transparent;
		border-right: 10rpx solid transparent;
		border-bottom: 20rpx solid red;
	}
</style>
